from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from utils.verify.captcha import captcha
from utils.verify.yuntongxun.sms import CCP
from utils.response_code import Code, ResultResponse
from django_redis import get_redis_connection
import logging
from users.models import User
import json
import random


logger = logging.getLogger("django")


# Create your views here.
def send_image_code(request, image_id):
    text, image = captcha.generate_captcha()
    redis_conn = get_redis_connection('image-verify')
    redis_conn.setex("img_{}".format(image_id), 60, text)
    logger.info(text)
    return HttpResponse(image, content_type="image/jpeg", status=200)


def check_username_repeat(request, username):
    c = User.objects.filter(username=username).count()
    data = {'count': c, 'username': username}
    return JsonResponse({'data': data})


def check_mobile_repeat(request, mobile):
    m = User.objects.filter(mobile=mobile).count()
    data = {'count': m, 'mobile': mobile}
    return JsonResponse({'data': data})


def check_sms_code(request):
    if request.method == "POST":
        json_str = request.body
        data = json.loads(json_str)
        image_code_client = data.get('text')
        uuid = data.get('image_code_id')
        mobile = data.get('mobile')
        print(image_code_client, uuid, mobile)
        if not all([image_code_client, uuid, mobile]):
            return ResultResponse(errno=Code.ERRPARAMS, errmsg='参数错误')
        # 校验参数
        # 连接到内存数据库
        redis_conn = get_redis_connection("image-verify")
        # 提取数据库中的图形验证码
        image_code_server = redis_conn.get("img_%s" % uuid)
        print(image_code_server)
        if image_code_server is None:
            # 图形验证码国旗或者不存在
            return ResultResponse(errno=Code.ERRPARAMS, errmsg='参数错误')
        # try:
        #     redis_conn.delete("img_%s" % uuid)
        # except Exception as e:
        #     logger.error(e)
        # 对比图形验证码
        image_code_server = image_code_server.decode()
        if image_code_client.lower() != image_code_server.lower():
            return ResultResponse(errno=Code.ERRVERIFY, errmsg='图形验证码错误')

        # 生成短信验证码，生成6位数验证码
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info(sms_code)

        # 限定频繁发送验证码
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return ResultResponse(errno=Code.ERRBUSY, errmsg='请求频繁')
        redis_conn.setex("sms_%s" % mobile, 60, sms_code)
        # 重新写入send_flag
        redis_conn.setex("send_flag_%s" % mobile, 60, 1)
        # 执行请求，发送短信
        logger.info("短信验证码：{}".format(sms_code))
        logger.info("发送短信正常[mobile:%s sms_num:%s]" % (mobile, sms_code))
        # 发送短信验证码
        ccp = CCP()
        ccp.send_template_sms("15871687941", [sms_code, 5], 1)
        # 响应结果
        return ResultResponse(errmsg='验证码发送成功')
